package com.example.she.lol;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import java.util.ArrayList;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import com.example.she.lol.anim.SelEffectAnim;
import com.github.jootnet.mir2.core.*;
import com.github.jootnet.mir2.core.image.*;
import com.example.she.lol.anim.CharSelAnim;
import android.graphics.Matrix;

/**
 * Created by she on 2017/11/10.
 */

public class ChrSelView extends SurfaceView implements Runnable, Callback{
    private SurfaceHolder holder;
    private Canvas canvas;
    private Thread mainT;
    private Context context;
    private  static boolean isRunning = false;

    private int SWidth = 0;
    private int SHeight = 0;

    private Boolean isShowProcess = false;

    //SurfaceView实例本身，方便线程中调用
    public static SurfaceView chrView;
    //ex > 400 && ex < 800 && ey > 150 && ey < 800
    private int rLeft = 400;
    private int rRight = 800;
    private int rTop = 100;
    private int rBottom = 750;

    public static String curRole = "TS";

    private void setFirstRole(){
        this.rLeft = 400;
        this.rRight = 800;
        this.rTop = 100;
        this.rBottom = 750;
        curRole = "TS";
    }

    private void setSecondRole(){
        //1100,150,1500,800
        this.rLeft = 1100;
        this.rRight = 1500;
        this.rTop = 100;
        this.rBottom = 750;
        curRole = "EM";
    }

    public ChrSelView(Context context) {
        super(context);
        this.setFocusable(true);
        this.context = context;
        setFocusableInTouchMode(true);
        holder = this.getHolder();//这个this指的是这个Surface
        holder.addCallback(this); //这个this表示实现了Callback接口
    }

    public ChrSelView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.setFocusable(true);
        this.context = context;
        setFocusableInTouchMode(true);
        holder = this.getHolder();//这个this指的是这个Surface
        holder.addCallback(this); //这个this表示实现了Callback接口
    }

    public ChrSelView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.setFocusable(true);
        this.context = context;
        setFocusableInTouchMode(true);
        holder = this.getHolder();//这个this指的是这个Surface
        holder.addCallback(this); //这个this表示实现了Callback接口
    }

    static String  sdCardRoot = "";
    ArrayList<Bitmap> bmpZS = new ArrayList<Bitmap>();
    ArrayList<Bitmap> bmpSZ = new ArrayList<Bitmap>();

    ArrayList<Bitmap> bmpTZ = new ArrayList<Bitmap>();
    ArrayList<Bitmap> bmpTS = new ArrayList<Bitmap>();

    ArrayList<Bitmap> bmpFS = new ArrayList<Bitmap>();
    ArrayList<Bitmap> bmpEM = new ArrayList<Bitmap>();

    CharSelAnim selAnimZS = null;
    CharSelAnim selAnimSZ = null;
    CharSelAnim selAnimTZ = null;
    CharSelAnim selAnimTS = null;
    CharSelAnim selAnimFS = null;
    CharSelAnim selAnimEM = null;

    SelEffectAnim selEffectAnim = null;
    private void loadChrSelImg() {
        //加载图片
        if (getDefaultFilePath() == ""){
            InputStream iFile = getResources().openRawResource(R.raw.chrsel);
            writeData2SDCard("lol", "chrsel.wil", iFile);
        }
        if (getMagicFilePath() == ""){
            InputStream iFile = getResources().openRawResource(R.raw.magic);
            writeData2SDCard("lol", "magic.wil", iFile);
        }
        WIL.GLOBAL_ONLYWIL_MODE = true;
        WIL wil = new WIL(sdCardRoot + File.separator + "lol" + File.separator + "chrsel.wil");

        WIL wilm = new WIL(sdCardRoot + File.separator + "lol" + File.separator + "magic.wil");

        /*
        for(int i=40;i<56;i++){
            Texture img = wil.tex(i);
            //ImageInfo curImgInfo = wil.info(i);
            Bitmap bmp = decodeFrameToBitmap(img.getRGBs(), img.getWidth(), img.getHeight());
            bmpZS.add(scaleBitmap(bmp,(float)1.5));
        }
        selAnimZS = new CharSelAnim(context,bmpZS);

        for(int i=160;i<176;i++){
            Texture img = wil.tex(i);
            Bitmap bmp = decodeFrameToBitmap(img.getRGBs(), img.getWidth(), img.getHeight());
            bmpSZ.add(scaleBitmap(bmp,(float)1.5));
        }
        selAnimSZ = new CharSelAnim(context,bmpSZ);

        for(int i=120;i<136;i++){
            Texture img = wil.tex(i);
            Bitmap bmp = decodeFrameToBitmap(img.getRGBs(), img.getWidth(), img.getHeight());
            bmpTZ.add(scaleBitmap(bmp,(float)1.5));
        }
        selAnimTZ = new CharSelAnim(context,bmpTZ);
        */

        for(int i=240;i<256;i++){
            Texture img = wil.tex(i);
            Bitmap bmp = decodeFrameToBitmap(img.getRGBs(), img.getWidth(), img.getHeight());
            bmpTS.add(scaleBitmap(bmp,(float)2));
        }
        selAnimTS = new CharSelAnim(context,bmpTS);

        /*
        for(int i=80;i<96;i++){
            Texture img = wil.tex(i);
            Bitmap bmp = decodeFrameToBitmap(img.getRGBs(), img.getWidth(), img.getHeight());
            bmpFS.add(scaleBitmap(bmp,(float)1.5));
        }
        selAnimFS = new CharSelAnim(context,bmpFS);
        */

        for(int i=200;i<216;i++){
            Texture img = wil.tex(i);
            Bitmap bmp = decodeFrameToBitmap(img.getRGBs(), img.getWidth(), img.getHeight());
            bmpEM.add(scaleBitmap(bmp,(float)2));
        }
        selAnimEM = new CharSelAnim(context,bmpEM);

        /*
        ArrayList<Bitmap> bmpSelEffect = new ArrayList<Bitmap>();
        for(int i=4;i<18;i++){
            Texture img = wil.tex(i);
            Bitmap bmp = decodeFrameToBitmap(img.getRGBs(), img.getWidth(), img.getHeight());
            bmpSelEffect.add(scaleBitmap(bmp,(float)1.5));
        }
        selEffectAnim = new SelEffectAnim(context,bmpSelEffect);
        */
    }

    /**
     * 按比例缩放图片
     *
     * @param origin 原图
     * @param ratio  比例
     * @return 新的bitmap
     */
    private Bitmap scaleBitmap(Bitmap origin, float ratio) {
        if (origin == null) {
            return null;
        }
        int width = origin.getWidth();
        int height = origin.getHeight();
        Matrix matrix = new Matrix();
        matrix.preScale(ratio, ratio);
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (newBM.equals(origin)) {
            return newBM;
        }
        origin.recycle();
        return newBM;
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        sdCardRoot = Environment.getExternalStorageDirectory().getAbsolutePath();
        //初始化高度和宽度
        SWidth = this.getWidth();
        SHeight = this.getHeight();
        loadChrSelImg();
        mainT = new Thread(this);
        mainT.start();
        isRunning = true;
    }


    public static int convertByteToInt(byte data){
        int heightBit = (int) ((data>>4) & 0x0F);
        int lowBit = (int) (0x0F & data);
        return heightBit * 16 + lowBit;
    }

    public static int[] convertByteToColor(byte[] data){
        int size = data.length;
        if (size == 0){
            return null;
        }

        int arg = 0;
        if (size % 3 != 0){
            arg = 1;
        }

        int []color = new int[size / 3 + arg];
        int red, green, blue;

        if (arg == 0){
            for(int i = 0; i < color.length; ++i){
                red = convertByteToInt(data[i * 3]);
                green = convertByteToInt(data[i * 3 + 1]);
                blue = convertByteToInt(data[i * 3 + 2]);
                if (red ==0 && green ==0 && blue==0){
                    color[i] = (red << 16) | (green << 8) | blue | 0x00000000;
                }else{
                    color[i] = (red << 16) | (green << 8) | blue | 0xFF000000;
                }

            }
        }else{
            for(int i = 0; i < color.length - 1; ++i){
                red = convertByteToInt(data[i * 3]);
                green = convertByteToInt(data[i * 3 + 1]);
                blue = convertByteToInt(data[i * 3 + 2]);
                if (red ==0 && green ==0 && blue==0){
                    color[i] = (red << 16) | (green << 8) | blue | 0x00000000;
                }else{
                    color[i] = (red << 16) | (green << 8) | blue | 0xFF000000;
                }
            }

            color[color.length - 1] = 0xFF000000;
        }

        return color;
    }
    Bitmap decodeFrameToBitmap(byte[] frame, int w, int h)
    {
        int []colors = convertByteToColor(frame);
        if (colors == null){
            return null;
        }
        Bitmap bmp = Bitmap.createBitmap(colors, 0, w, w, h,Bitmap.Config.ARGB_8888);
        return bmp;
    }

    /**
     * 获取默认的文件路径
     *
     * @return
     */
    public static String getDefaultFilePath() {
        String filepath = "";
        File file = new File(sdCardRoot + File.separator + "lol" + File.separator, "chrsel.wil");
        if (file.exists()) {
            filepath = file.getAbsolutePath();
        }
        return filepath;
    }

    public static String getMagicFilePath() {
        String filepath = "";
        File file = new File(sdCardRoot + File.separator + "lol" + File.separator, "magic.wil");
        if (file.exists()) {
            filepath = file.getAbsolutePath();
        }
        return filepath;
    }

    /**
     * 在SD卡上创建目录
     */
    public File createDirOnSDCard(String dir)
    {
        File dirFile = new File(sdCardRoot + File.separator + dir +File.separator);
        dirFile.mkdirs();
        return dirFile;
    }

    /**
     * 在SD卡上创建文件
     */
    public File createFileOnSDCard(String fileName, String dir) throws IOException
    {
        File file = new File(sdCardRoot + File.separator + dir + File.separator + fileName);
        file.createNewFile();
        return file;
    }

    /* 写入数据到SD卡中
     */
    public File writeData2SDCard(String path, String fileName, InputStream data)
    {
        File file = null;
        OutputStream output = null;

        try {
            createDirOnSDCard(path);  //创建目录
            file = createFileOnSDCard(fileName, path);  //创建文件
            output = new FileOutputStream(file);
            byte buffer[] = new byte[2*1024];          //每次写2K数据
            int temp;
            while((temp = data.read(buffer)) != -1 )
            {
                output.write(buffer,0,temp);
            }
            output.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }
        finally{
            try {
                output.close();    //关闭数据流操作
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return file;
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        isRunning = false;
    }

    @Override
    public void run() {
        while (isRunning) {
            drawView();
        }
    }

    private void drawView() {
        try
        {
            if (holder != null)
            {
                Paint p = new Paint();

                //打底色
                canvas = holder.lockCanvas();
                if (canvas == null){return;}
                //canvas.drawARGB(255, 32, 48, 16);
                canvas.drawColor(Color.DKGRAY);
                Paint p1 = new Paint();
                p1.setColor(Color.rgb(255,215,0));
                p1.setStyle(Paint.Style.STROKE);
                p1.setStrokeWidth(20);
                canvas.drawRoundRect(this.rLeft,this.rTop,this.rRight,this.rBottom,10,10,p1);

                //中间的角色展示
                /*if (selAnimZS != null){
                    selAnimZS.Run(canvas, 150, 20);
                }
                if (selAnimSZ != null){
                    selAnimSZ.Run(canvas, 150, 520);
                }

                if (selAnimTZ != null){
                    selAnimTZ.Run(canvas, 700, 30);
                }
                */

                if (selAnimTS != null){
                    selAnimTS.Run(canvas, 400, 100);
                }
                /*
                if (selAnimFS != null){
                    selAnimFS.Run(canvas, 1250, 10);
                }*/

                if (selAnimEM != null){
                    selAnimEM.Run(canvas, 1100, 100);
                }
                /*
                if (selEffectAnim != null){
                    selEffectAnim.Run(canvas, 1300, 500);
                }
                */

                //下面的进入按钮
                p1.setColor(Color.WHITE);
                p1.setStyle(Paint.Style.STROKE);
                p1.setStrokeWidth(2);
                canvas.drawRoundRect(700,900,1300,1000,10,10, p1);
                p1.setStyle(Paint.Style.FILL);
                p1.setTextSize(60);
                canvas.drawText("进入游戏",870,970,p1);

                if (isShowProcess){
                    p1.setColor(Color.BLUE);
                    canvas.drawRoundRect(400, 810, 1400, 860,10,10,p1);
                    p1.setColor(Color.GREEN);
                    canvas.drawRoundRect(400, 810, 400 + 1000 * GameView.loadPercenter/100 , 860,10,10,p1);
                }
            }

        } catch (Exception e)
        {
            e.printStackTrace();
        } finally
        {
            if (canvas != null)
                holder.unlockCanvasAndPost(canvas);
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event)
    {
        float ex = event.getX();
        float ey = event.getY();
        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:{
                break;
            }
            case MotionEvent.ACTION_DOWN:{
                if (ex > 700 && ex < 1300 && ey >900 && ey < 1000){
                    if (!isShowProcess){
                        //线程加载完成之后回调主程序的setView方法，比较高端
                        isShowProcess = true;
                        ChrSelView.chrView = this;
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 耗时操作
                                GameView.loadActor(ChrSelView.chrView);
                                ChrSelView.chrView.post(new Runnable(){
                                    @Override
                                    public void run() {
                                        if (GameView.loadPercenter == 100){
                                            MainActivity.CurActivity.setView();
                                        }
                                    }
                                });
                            }
                        }).start();
                    }
                }else if (ex > 400 && ex < 800 && ey > 150 && ey < 800){
                    if (!isShowProcess){
                        setFirstRole();
                    }

                }else if (ex > 1100 && ex < 1500 && ey > 150 && ey < 800){
                    if (!isShowProcess){
                        setSecondRole();
                    }
                }
                break;
            }
            case MotionEvent.ACTION_POINTER_DOWN:{
                break;
            }
        }
        return true;
    }
}